package com.sxt.demo.djiapplication.utils

import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import com.sxt.demo.djiapplication.BuildConfig
import java.io.File

object ShareUtil {

    /**
     * Android原生分享功能
     * 默认选取手机所有可以分享的APP
     */
    @JvmStatic
    fun allShare(shareIntentBuilder: ShareIntentBuilder) {
        shareIntentBuilder.context.startActivity(shareIntentBuilder.build())
    }

    class ShareIntentBuilder(val context: Context) {

        private val shareIntent = Intent()

        private var title = "分享到"

        init {
            // 设置分享行为
            shareIntent.action = Intent.ACTION_SEND
        }

        /**
         * 设置分享内容的类型
         */
        fun type(type: String): ShareIntentBuilder {
            shareIntent.type = type
            return this
        }

        /**
         * 添加分享内容标题
         */
        fun subject(subject: String): ShareIntentBuilder {
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
            return this
        }

        /**
         * 创建分享的对话框时的标题
         */
        fun title(title: String): ShareIntentBuilder {
            this.title = title
            return this
        }

        /**
         * 添加分享内容(文件)
         */
        @JvmOverloads
        fun content(value: File, name: String = Intent.EXTRA_STREAM): ShareIntentBuilder {
            shareIntent.type = FileUtil.getMIMEType(value)
            shareIntent.putExtra(
                name,
                FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.sxt", value)
            )
            shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            return this
        }

        fun build(): Intent {
            //            createChooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            return Intent.createChooser(shareIntent, title)
        }

    }
}